package com.heatup.apt.management.service.impl;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.heatup.apt.common.constants.TokenConstants;
import com.heatup.apt.common.dao.TokenMapper;
import com.heatup.apt.management.service.WechatMenuService;
import com.heatup.apt.management.util.ManageConfigPropertiesUtil;
import com.heatup.apt.management.util.message.Button;
import com.heatup.apt.management.util.message.ClassButton;
import com.heatup.apt.management.util.message.ComplexButton;
import com.heatup.apt.management.util.message.Menu;
import com.heatup.apt.management.util.message.ViewButton;

import net.sf.json.JSONObject;

/**
 * 微信菜单服务类
 * @author jixiangyun
 * 2016年12月5日 下午10:49:35
 */
@Service
public class WechatMenuServiceImpl implements WechatMenuService {
	Logger log = LoggerFactory.getLogger(WechatMenuServiceImpl.class);
	
	@Autowired
	private TokenMapper tokenMapper;

	/**
	 * 创建微信菜单
	 */
	@Override
	public Map<String, Object> createWechatMenu() {
		log.info("==================================create wechat menu satrt =====================================");
		Map<String, Object> map = new HashMap<String, Object>();
		// 1 获取accessToken
		// 根据环境生成对应的菜单
		String accessToken =  tokenMapper.selectTokenByKey(TokenConstants.ACCESS_TOKEN_KEY).getToken();
		int status = createMenu(getMenu(),accessToken);

		if(status == 0){
			map.put("status", 0);
			map.put("msg","创建成功");
			log.info("==================================create wechat menu is OK =====================================");
		}else{
			map.put("status", -1);
			map.put("msg","创建失败");
			log.info("==================================create wechat menu is error =====================================");
		}
		log.info("==================================create wechat menu end =====================================");
		return map;
	}
	
	/**
	 * 创建自定义菜单(每天限制1000次)
	 * */
	public  int createMenu(Menu menu,String accessToken) {
		String jsonMenu = JSONObject.fromObject(menu).toString();
		int status = 0;
		String path = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token="
				+ accessToken;
		try {
			URL url = new URL(path);
			HttpURLConnection http = (HttpURLConnection) url.openConnection();
			http.setDoOutput(true);
			http.setDoInput(true);
			http.setRequestMethod("POST");
			http.setRequestProperty("Content-Type",
					"application/x-www-form-urlencoded");
			http.connect();
			OutputStream os = http.getOutputStream();
			os.write(jsonMenu.getBytes("UTF-8"));
			os.close();

			InputStream is = http.getInputStream();
			int size = is.available();
			byte[] bt = new byte[size];
			is.read(bt);
			String message = new String(bt, "UTF-8");
			JSONObject jsonMsg = JSONObject.fromObject(message);
			log.info("jsonMsg:"+jsonMsg);
			status = Integer.parseInt(jsonMsg.getString("errcode"));
		} catch (MalformedURLException e) {
//			e.printStackTrace();
			log.error("================= createMenu error:"+e.toString()+e.getCause(),e);
		} catch (IOException e) {
//			e.printStackTrace();
			log.error("================= createMenu error:"+e.toString()+e.getCause(),e);
		}
		return status;
	}
	
	/**
	 * 设置菜单： 一级菜单只能是小于或者等于三 
	 * @return
	 */
	public Menu getMenu() {
		
		String yygh = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxe4dfc45a9f29fb8b&redirect_uri=http%3A%2F%2Ftest.heatup.cn%2Fapi%2Fredirect%2FweiXinJump%3Fpath%3D%2Fhome%2Frecommendation%26scopetepm%3Dsnsapi_userinfo&response_type=code&scope=snsapi_userinfo&state=123&connect_redirect=1#wechat_redirect";
		String wdgh = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxe4dfc45a9f29fb8b&redirect_uri=http%3A%2F%2Ftest.heatup.cn%2Fapi%2Fredirect%2FweiXinJump%3Fpath%3D%2Fhome%2Frecommendation%26scopetepm%3Dsnsapi_userinfo&response_type=code&scope=snsapi_userinfo&state=123&connect_redirect=1#wechat_redirect";
		String jiaolian = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxe4dfc45a9f29fb8b&redirect_uri=http%3A%2F%2Ftest.heatup.cn%2Fapi%2Fredirect%2FweiXinJump%3Fpath%3D%2Fphone_bind&response_type=code&scope=snsapi_userinfo&state=321#wechat_redirect";
		Menu menu = new Menu();
	
		// 一级菜单
		ClassButton classButton = new ClassButton();
		classButton.setName("预约服务");
		classButton.setType("view");
		classButton.setUrl(ManageConfigPropertiesUtil.getString("home_page_url").trim());
		
		ViewButton vb1 = new ViewButton();
		vb1.setName("我的会员");
		vb1.setType("view");
		vb1.setUrl(ManageConfigPropertiesUtil.getString("fopen_vip").trim());
		
		ViewButton vb2 = new ViewButton();
		vb2.setName("我的预约");
		vb2.setType("view");
		vb2.setUrl(ManageConfigPropertiesUtil.getString("fbefore_team").trim());
		
		ViewButton vb3 = new ViewButton();
		vb3.setName("我的优惠券");
		vb3.setType("view");
		vb3.setUrl(ManageConfigPropertiesUtil.getString("coupon_urls").trim());
		
		ViewButton vb4 = new ViewButton();
		vb4.setName("我的代金卡");
		vb4.setType("view");
		vb4.setUrl(ManageConfigPropertiesUtil.getString("cashcard").trim());
		
		ViewButton vb5 = new ViewButton();
		vb5.setName("邀请好友");
		vb5.setType("view");
		vb5.setUrl(ManageConfigPropertiesUtil.getString("invite_friends").trim());
		
		ViewButton vc3 = new ViewButton();
		vc3.setName("我的锻炼");
		vc3.setType("view");
		vc3.setUrl("http://www.fizzo.cn/fizzoh5/check_cookie_for_weixin_oauth_include.php?state=%2Ffizzoh5%2FtrainingRecord.html%3Fstoreid%3D213");
		
		ComplexButton cx_2 = new ComplexButton();
		cx_2.setName("我的");
		
		
		/*ViewButton vc1 = new ViewButton();
		vc1.setName("教练精选");
		vc1.setType("view");
		vc1.setUrl("http://mp.weixin.qq.com/mp/homepage?__biz=MzIyMTQ5MDg2OQ==&hid=1&sn=5e5bdf3ea4427658181e72a34c3f8669#wechat_redirect");*/
		
		ViewButton vc2 = new ViewButton();
		vc2.setName("我是教练");
		vc2.setType("view");
		vc2.setUrl(ManageConfigPropertiesUtil.getString("my_is_coach").trim());
		
		ComplexButton cx_3 = new ComplexButton();
		cx_3.setName("围裙教练");
		
		
		cx_2.setSub_button(new Button[] { vb1, vb2, vb3, vb4,vb5 });//,vb3, vb4 
		cx_3.setSub_button(new Button[] {  vc2, vc3});
		menu.setButton(new Button[] { classButton, cx_3,cx_2});
		return menu;
	}
	
	/**
	 * 本地生成线上的菜单
	 * @return
	 */
	public static Menu getMenuRelease(){
		//#团课链接
		String fteam_course= "https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx65db45e85c1be9c4&redirect_uri=http%3A%2F%2Fh5.heatup.cn%2Fapi%2Fredirect%2FweiXinJump%3Fpath%3D%2Fhome%2Fteam_course&response_type=code&scope=snsapi_userinfo&state=123&connect_redirect=1#wechat_redirect"; 
		//#私教课
		String fpersonal_course= "https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx65db45e85c1be9c4&redirect_uri=http%3A%2F%2Fh5.heatup.cn%2Fapi%2Fredirect%2FweiXinJump%3Fpath%3D%2Fhome%2Fpersonal_course&response_type=code&scope=snsapi_userinfo&state=123&connect_redirect=1#wechat_redirect";
		//#小班训练营
		String fcamp_course= "https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx65db45e85c1be9c4&redirect_uri=http%3A%2F%2Fh5.heatup.cn%2Fapi%2Fredirect%2FweiXinJump%3Fpath%3D%2Fhome%2Fcamp_course&response_type=code&scope=snsapi_userinfo&state=123&connect_redirect=1#wechat_redirect";	
		//#自助健身
		String fself_game= "https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx65db45e85c1be9c4&redirect_uri=http%3A%2F%2Fh5.heatup.cn%2Fapi%2Fredirect%2FweiXinJump%3Fpath%3D%2Fhome%2Fself_game&response_type=code&scope=snsapi_userinfo&state=123&connect_redirect=1#wechat_redirect";	
		//#开通会员
		String fopen_vip= "https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx65db45e85c1be9c4&redirect_uri=http%3A%2F%2Fh5.heatup.cn%2Fapi%2Fredirect%2FweiXinJump%3Fpath%3D%2Fhome%2Fmy_vip&response_type=code&scope=snsapi_userinfo&state=123&connect_redirect=1#wechat_redirect";	
		//#我的特权
		String fopen_privilege = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx65db45e85c1be9c4&redirect_uri=http%3A%2F%2Fh5.heatup.cn%2Fapi%2Fredirect%2FweiXinJump%3Fpath%3D%2Fhome%2Fopen_vip&response_type=code&scope=snsapi_userinfo&state=123&connect_redirect=1#wechat_redirect";
		//#我的预约
		String fbefore_team = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx65db45e85c1be9c4&redirect_uri=http%3A%2F%2Fh5.heatup.cn%2Fapi%2Fredirect%2FweiXinJump%3Fpath%3D%2Fhome%2Fbefore_team&response_type=code&scope=snsapi_userinfo&state=123&connect_redirect=1#wechat_redirect";
		//#联系小檬
		//#檬店 | 健身咖
		String fstore_list= "https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx65db45e85c1be9c4&redirect_uri=http%3A%2F%2Fh5.heatup.cn%2Fapi%2Fredirect%2FweiXinJump%3Fpath%3D%2Fhome%2Fstore_list&response_type=code&scope=snsapi_userinfo&state=123&connect_redirect=1#wechat_redirect";	
		//#星探 | 教练招募
		String coach_url= "http://mp.weixin.qq.com/s?__biz=MzIyMTQ5MDg2OQ==&mid=2247484813&idx=1&sn=b55a2a61593160b09d70b723471fd7bb&chksm=e83abe57df4d374182d8de873d27920cc5cc1edfe1fd925623af3331c8b628add6abd23a733e&mpshare=1&scene=1&srcid=1111zW2QqYvMGWw9NonJYNXE#wechat_redirect";	
		//#新晋檬蜜入门指南
		String mengmi= "http://mp.weixin.qq.com/s/JnguLQZNtz0maqgbu7a7QQ";	
		//#过往文章
		String article_url= "http://mp.weixin.qq.com/mp/getmasssendmsg?__biz=MzIyMTQ5MDg2OQ==&from=1#wechat_webview_type=1&wechat_redirect";
		//#邀请好友
		String invite_friends= "https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx65db45e85c1be9c4&redirect_uri=http%3A%2F%2Fh5.heatup.cn%2Fapi%2Fredirect%2FweiXinJump%3Fpath%3D%2Fhome%2Finvite_new&response_type=code&scope=snsapi_userinfo&state=123&connect_redirect=1#wechat_redirect"; 
		//#我的优惠券列表
		String coupon_urls = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx65db45e85c1be9c4&redirect_uri=http%3A%2F%2Fh5.heatup.cn%2Fapi%2Fredirect%2FweiXinJump%3Fpath%3D%2Fhome%2Fcoupon_list%26scopetepm%3Dsnsapi_base&response_type=code&scope=snsapi_userinfo&state=123&connect_redirect=1#wechat_redirect";
		//#常见问题
		String FAQ= "https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx65db45e85c1be9c4&redirect_uri=http%3A%2F%2Fh5.heatup.cn%2Fapi%2Fredirect%2FweiXinJump%3Fpath%3D%2Fhome%2Fhelp_center%26scopetepm%3Dsnsapi_base&response_type=code&scope=snsapi_userinfo&state=123&connect_redirect=1#wechat_redirect";
		//#我是教练 
		String my_is_coach = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx65db45e85c1be9c4&redirect_uri=http%3A%2F%2Fh5.heatup.cn%2Fapi%2Fredirect%2FweiXinJump%3Fpath%3D%2Flevel_page%2Fteam_course%26scopetepm%3Dsnsapi_base&response_type=code&scope=snsapi_userinfo&state=123&connect_redirect=1#wechat_redirect";  
		//#代金卡
		String cashcard= "https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx65db45e85c1be9c4&redirect_uri=http%3A%2F%2Fh5.heatup.cn%2Fapi%2Fredirect%2FweiXinJump%3Fpath%3D%2Fhome%2Fcard%26scopetepm%3Dsnsapi_userinfo&response_type=code&scope=snsapi_userinfo&state=123&connect_redirect=1#wechat_redirect";

		
		Menu menu = new Menu();
		// 设置二级菜单
		ViewButton cb1 = new ViewButton();
		cb1.setName("团体课");
		cb1.setType("view");
		cb1.setUrl(fteam_course.trim());

		ViewButton cb2 = new ViewButton();
		cb2.setName("私教课");
		cb2.setType("view");
		cb2.setUrl(fpersonal_course.trim());

		ViewButton cb3 = new ViewButton();
		cb3.setName("小班训练营");
		cb3.setType("view");
		cb3.setUrl(fcamp_course.trim());

		ViewButton cb4 = new ViewButton();
		cb4.setName("自助健身");
		cb4.setType("view");
		cb4.setUrl(fself_game.trim());
		
		ViewButton cb5 = new ViewButton();
		cb5.setName("檬店列表");
		cb5.setType("view");
		cb5.setUrl(fstore_list.trim());
		
		
		// 一级菜单
		ComplexButton cx_1 = new ComplexButton();
		cx_1.setName("预约课程");

		ViewButton vb1 = new ViewButton();
		vb1.setName("我的会员");
		vb1.setType("view");
		vb1.setUrl(fopen_vip.trim());
		
		ViewButton vb2 = new ViewButton();
		vb2.setName("我的预约");
		vb2.setType("view");
		vb2.setUrl(fbefore_team.trim());
		
		ViewButton vb3 = new ViewButton();
		vb3.setName("我的檬券");
		vb3.setType("view");
		vb3.setUrl(coupon_urls.trim());
		
		
		ViewButton vb4 = new ViewButton();
		vb4.setName("我的代金卡");
		vb4.setType("view");
		vb4.setUrl(cashcard.trim());
		
		ViewButton vb5 = new ViewButton();
		vb5.setName("邀请好友");
		vb5.setType("view");
		vb5.setUrl(invite_friends.trim());
		
		/*ViewButton vc3 = new ViewButton();
		vc3.setName("我要吐槽");
		vc3.setType("view");
		vc3.setUrl("https://tucao.qq.com/embed/7284");*/
		
		ComplexButton cx_2 = new ComplexButton();
		cx_2.setName("我的");
		
		
		
		ViewButton vc1 = new ViewButton();
		vc1.setName("教练精选");
		vc1.setType("view");
		vc1.setUrl("http://mp.weixin.qq.com/mp/homepage?__biz=MzIyMTQ5MDg2OQ==&hid=1&sn=5e5bdf3ea4427658181e72a34c3f8669#wechat_redirect");
		
		ViewButton vc2 = new ViewButton();
		vc2.setName("我是教练");
		vc2.setType("view");
		vc2.setUrl(my_is_coach.trim());
		
		ComplexButton cx_3 = new ComplexButton();
		cx_3.setName("檬教练");

		
		cx_2.setSub_button(new Button[] { vb1, vb2, vb3, vb4, vb5});//,vb3, vb4 
		cx_1.setSub_button(new Button[] { cb1, cb2, cb3, cb4,cb5});
		cx_3.setSub_button(new Button[] { vc1 , vc2});
		menu.setButton(new ComplexButton[] { cx_1, cx_3,cx_2});
		return menu;
	}
	
	/**
	 * 本地生成线上菜单
	 */
	@Override
	public Map<String, Object> createWechatMenuReal() {
		Map<String,Object> map = new HashMap<>();
		// 1 获取线上的accessToken
		String accessToken =  "dbxVhKMQM6TIW2pDy_fAqoqS3vfEOFZegFndwps6dTMG2ECEVYJAyBxU56Dw_NBALIA6L-Ag2HqQhHLPpE41sH8E7pe8WRaYyINwGI-9kScJQLiAAAMTO";
		// 2 创建菜单
		int status = createMenu(getMenuRelease(), accessToken);
		if(status == 0){
			map.put("status", 0);
			map.put("msg","创建成功");
			log.info("==================================create wechat menu is OK =====================================");
		}else{
			map.put("status", -1);
			map.put("msg","创建失败");
			log.info("==================================create wechat menu is error =====================================");
		}
		log.info("==================================create wechat menu end =====================================");
		return map;
	}

}
